package com.dao.impl;

// default package

import static org.hibernate.criterion.Example.create;

import java.math.BigInteger;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import com.dao.ProgrammingDao;
import com.model.Programming;
import com.model.User;
import com.util.Pagination;

/**
 * A data access object (DAO) providing persistence and search support for Programming entities. Transaction control of the save(), update() and delete() operations can directly
 * support Spring container-managed transactions or they can be augmented to handle user-managed Spring transactions. Each of these methods provides additional information for how
 * to configure it for the desired type of transaction control.
 * 
 * @see .Programming
 * @author MyEclipse Persistence Tools
 */
@Repository("ProgrammingDao")
public class ProgrammingDaoImpl implements ProgrammingDao {

    @Resource
    private SessionFactory sessionFactory;

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @Override
    public void save(Programming transientInstance) {
        try {
            Session session = sessionFactory.getCurrentSession();
            session.save(transientInstance);
        } catch (RuntimeException re) {
            throw re;
        }
    }

    @Override
    public void delete(Programming persistentInstance) {
        try {
            Session session = sessionFactory.getCurrentSession();
            session.delete(persistentInstance);
        } catch (RuntimeException re) {
            throw re;
        }
    }

    @Override
    public Programming findById(java.lang.Integer id) {
        try {
            Session session = sessionFactory.getCurrentSession();
            Programming instance = (Programming) session.get("com.model.Programming", id);
            return instance;
        } catch (RuntimeException re) {
            throw re;
        }
    }

    @Override
    public List<Programming> findByExample(Programming instance) {
        try {
            Session session = sessionFactory.getCurrentSession();
            List<Programming> results = session.createCriteria("com.model.Programming").add(create(instance)).list();
            return results;
        } catch (RuntimeException re) {
            throw re;
        }
    }

    @Override
    public List findAll() {
        try {
            Session session = sessionFactory.getCurrentSession();
            String queryString = "from Programming";
            Query queryObject = session.createQuery(queryString);
            return queryObject.list();
        } catch (RuntimeException re) {
            throw re;
        }
    }

    @Override
    public Programming merge(Programming detachedInstance) {
        try {
            Session session = sessionFactory.getCurrentSession();
            Programming result = (Programming) session.merge(detachedInstance);
            return result;
        } catch (RuntimeException re) {
            throw re;
        }
    }

    @Override
    public Pagination getProgrammingList(Programming programming, Pagination page, String papername, User loginUser) {
        boolean flag = true;
        Session session = sessionFactory.getCurrentSession();

        if (programming.getTitle() == null)
            programming.setTitle("");

        String hql = "from Programming p where p.prefix is null and p.title like '%" + programming.getTitle() + "%'";
        if (programming.getScore() == null)
            programming.setScore(-1);
        if (!programming.getTitle().trim().equals("") || programming.getScore() != -1) {
            hql = hql + " and p.prefix is null and p.visible = 0 ";
            flag = false;
        }
        if (programming.getScore() != (-1)) {

            hql = hql + " and p.prefix is null and p.score = " + programming.getScore();
        }

        if (!papername.equals("")) {
            User u = findUser(papername);
            if (u != null)
                if (u.getId() == loginUser.getId())
                    hql = hql + " and p.prefix is null and p.user.id =" + loginUser.getId();

                else {

                    hql = hql + " and p.prefix is null and p.visible = 0 and p.user.id =" + u.getId();
                }

        } else {
            if (flag)
                hql = hql + " and p.prefix is null and p.visible = 0 or p.user.id =" + loginUser.getId();
        }

        hql = hql + " and p.prefix is null";
        Query query = session.createQuery(hql);
        page.setTotal(query.list().size());
        query.setFirstResult((page.getCurrentpage() - 1) * page.getPagesize());
        query.setMaxResults(30);
        List list = query.list();
        page.setTotalpagecountByhand();
        page.setList(list);
        return page;

    }

    public User findUser(String papername) {
        Session session = sessionFactory.getCurrentSession();
        String queryString = "from User u where u.username = '" + papername + "'";
        Query q = session.createQuery(queryString);
        if (q.list().size() != 0)
            return (User) q.list().get(0);
        else {
            User u = null;
            return u;
        }
    }

    @Override
    public int countProgramming(Programming programming) {
        Session session = sessionFactory.getCurrentSession();
        String queryString = "from Programming";
        Query queryObject = session.createQuery(queryString);
        return queryObject.list().size();

    }

    @Override
    public Programming findProgram(Programming program) {
        Session session = sessionFactory.getCurrentSession();
        List<Programming> results = session.createCriteria("com.model.Programming").add(create(program)).list();
        return results.get(0);
    }

    @Override
    public void ProgramDel(String id) {

        Session session = sessionFactory.getCurrentSession();
        session.createQuery("delete from Programming p where p.id=" + id).executeUpdate();

    }

    @Override
    public Pagination getProgrammingBlankList(Programming programming, Pagination page, String papername, User loginUser) {
        boolean flag = true;
        Session session = sessionFactory.getCurrentSession();

        if (programming.getTitle() == null)
            programming.setTitle("");

        String hql = "from Programming p where p.title like '%" + programming.getTitle() + "%'";
        if (programming.getScore() == null)
            programming.setScore(-1);
        if (!programming.getTitle().trim().equals("") || programming.getScore() != -1) {
            hql = hql + " and p.prefix is not null and p.visible = 0 ";
            flag = false;
        }
        if (programming.getScore() != (-1)) {

            hql = hql + " and p.prefix is not null and p.score = " + programming.getScore();
        }

        if (!papername.equals("")) {
            User u = findUser(papername);
            if (u != null)
                if (u.getId() == loginUser.getId())
                    hql = hql + " and p.prefix is not null and p.user.id =" + loginUser.getId();

                else {

                    hql = hql + " and p.prefix is not null and p.visible = 0 and p.user.id =" + u.getId();
                }

        } else {
            if (flag)
                hql = hql + " and p.prefix is not null and p.visible = 0 or p.user.id =" + loginUser.getId();
        }

        hql = hql + " and p.prefix is not null";
        Query query = session.createQuery(hql);
        page.setTotal(query.list().size());
        query.setFirstResult((page.getCurrentpage() - 1) * page.getPagesize());
        query.setMaxResults(30);
        List list = query.list();
        System.out.println(list.size());
        page.setTotalpagecountByhand();
        page.setList(list);
        return page;

    }

    @Override
    public Programming findById(BigInteger id) {
        try {
            Session session = sessionFactory.getCurrentSession();
            Programming instance = (Programming) session.get("com.model.Programming", id.intValue());
            return instance;
        } catch (RuntimeException re) {
            throw re;
        }
    }

}